/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年8月16日
 */
package com.massyframework.beanskin.sample.plugin;

import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.util.List;

import com.massyframework.beanskin.Module;
import com.massyframework.beanskin.ModuleCreatedEvent;
import com.massyframework.beanskin.ModuleDestoryingEvent;
import com.massyframework.beanskin.ModuleEventAdapter;
import com.massyframework.beanskin.fragment.Fragment;
import com.massyframework.beanskin.sample.SayHello;
import com.massyframework.beanskin.service.ServiceRegistry;
import com.massyframework.beanskin.service.ServiceRepository;
import com.massyframework.beanskin.util.BeanSkinServiceLoaderUtils;

/**
 * 片段监听器
 * 
 * @author huangkh
 *
 */
public class FragmentMonitor extends ModuleEventAdapter {

	/**
	 * 
	 */
	public FragmentMonitor() {

	}

	@Override
	protected void onCreated(ModuleCreatedEvent event) {
		Module<?> module = event.getModule();
		if (module instanceof Fragment) {	
			
			List<SayHello> list = BeanSkinServiceLoaderUtils.loadServies(SayHello.class,module.getModuleClassLoader()); 
			if (!list.isEmpty()) { 
				ServiceRepository repo =ServiceRepository.retrieveFrom(module); 
				Instrumentation inst = repo.getService(Instrumentation.class);
				ServiceRegistry registry =repo.getServiceRegistry(); 
				Class<?>[] types = new Class<?>[list.size()];
				int index = 0;
				for (SayHello service : list) {
					registry.register(SayHello.class,service, null); 
					service.instrumentTest(inst);
					
					types[index] = service.getClass();
					index++;
				}  	
				list.clear();
				
				try {
					for (Class<?> clazz: types) {
						if (inst.isModifiableClass(clazz)) {
							inst.retransformClasses(clazz);
						}
					}
				} catch (UnmodifiableClassException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	protected void onDestorying(ModuleDestoryingEvent event) {
		super.onDestorying(event);
	}

}
